package com.atguigu.aclservice.service.impl;

import com.atguigu.aclservice.mapper.UserMapper;
import com.atguigu.aclservice.service.PermissionService;
import com.atguigu.serurity.entity.LoginUser;
import com.atguigu.serurity.entity.User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 实现spring-security默认的验证用户信息的方式-》默认是去内存中查找username和password
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

	@Resource
	private UserMapper userMapper;

	@Resource
	private PermissionService permissionService;

	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		/**
		 *
		 */
		LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(User::getUsername, userName);
		User user = userMapper.selectOne(lambdaQueryWrapper);
		/*如果没有查询到用户，抛出异常
		if (Objects.isNull(user)) {
			throw new RuntimeException("用户不存在");
		}*/


		// 判断用户是否存在
		if (null == user){
			throw new UsernameNotFoundException("用户名不存在！");
		}

		List<String> authorities = permissionService.selectPermissionValueByUserId(user.getId());

		return new LoginUser(user,authorities);
	}

}
